﻿Imports System.Text

' Inclusion of PEAK PCAN-Basic namespace
'
Imports Peak.Can.Basic
Imports TPCANHandle = System.UInt16
Imports TPCANBitrateFD = System.String
Imports TPCANTimestampFD = System.UInt64
Imports System.Threading
Imports System.IO
Imports Microsoft.Office.Interop
Imports OxyPlot
Imports OxyPlot.Series

Public Class Form_ReadEEPROMMainPage

#Region "Delegates"
    ''' <summary>
    ''' Read-Delegate Handler
    ''' </summary>
    Private Delegate Sub ReadDelegateHandler()
#End Region

#Region "Members"
    Public MarcoPaola As New MacroPalo
    Private m_IsFD As Boolean
    ''' <summary>
    ''' Saves the handle of a PCAN hardware
    ''' </summary>
    Private m_PcanHandle As TPCANHandle
    ''' <summary>
    ''' Saves the baudrate register for a conenction
    ''' </summary>
    Private m_Baudrate As TPCANBaudrate
    ''' <summary>
    ''' Saves the type of a non-plug-and-play hardware
    ''' </summary>
    Private m_HwType As TPCANType
    ''' <summary>
    ''' Stores the status of received messages for its display
    ''' </summary>
    Public m_LastMsgsList As New System.Collections.ArrayList
    ''' <summary>
    ''' Read Delegate for calling the function "ReadMessages"
    ''' </summary>
    Private m_ReadDelegate As ReadDelegateHandler
    ''' <summary>
    ''' Receive-Event
    ''' </summary>
    Private m_ReceiveEvent As System.Threading.AutoResetEvent
    ''' <summary>
    ''' Thread for message reading (using events)
    ''' </summary>
    Public m_ReadThread As System.Threading.Thread

    Public m_SendTread As Thread
    ''' <summary>
    ''' Handles of the current available PCAN-Hardware
    ''' </summary>
    Private m_HandlesArray As TPCANHandle()
    Public m_FeedBackResults As FeedbackResults

    Private m_isCyclycal As Boolean


    Public ConnectionStatus As Boolean = False


    Public ParameterChangeringLogs As New ParamterLogList
    Public m_SWversionInACT As String
    Public m_SerialNumberInACT As String

    Public m_CANMatrix As CAN_Matrix = New CAN_Matrix

    Public m_TimeSincePowerOn As String
    Public m_TimesPowerOn As String


    Public isCommucationStopped As Boolean = False
    Public myprogress As Dialog_progress
    Public IDHere As String = ""

    Public DiagTableArray(m_CANMatrix.DiagnoticRowNumber, 16) As String
    Public RingBufferArray1(m_CANMatrix.RingBufferRowNumber, 16) As String
    Public RingBufferArray2(m_CANMatrix.RingBufferRowNumber, 16) As String
    Public HistogrimArray(m_CANMatrix.HistogramRowNumber) As String
    Public Property IsHistogramReadingFinished As Boolean

#End Region
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.ButtonGenerateReport.Enabled = False
        Me.ButtonRelease.Enabled = False
        ContextMenuStrip1.Enabled = False

        Try
            If Not Directory.Exists("CANMAX Library") Then
                Directory.CreateDirectory("CANMAX Library")
            End If

            Dim CANMM As CANMAX = New CANMAX(m_CANMatrix, m_FeedBackResults)

            Dim NameFile As String = m_CANMatrix.ClientName & "_" & m_CANMatrix.OMEName & "_" & m_CANMatrix.ApplicationName & "_" & m_CANMatrix.SWVersion & "_" & "TCI_" & m_CANMatrix.TCIVersion

            Me.MarcoPaola.ExportFileInfixedLocation("CANMAX", "CANMAX Library", CANMM, NameFile)
        Catch ex As Exception
            MsgBox("CANMAX Library can not be created, Failure of system access")
        End Try

        Try
            If Not Directory.Exists("Log") Then
                Directory.CreateDirectory("Log")


                Try
                    Dim NameFile As String = m_CANMatrix.ClientName & "_" & m_CANMatrix.OMEName & "_" & m_CANMatrix.ApplicationName & "_" & m_CANMatrix.SWVersion & "_" & "TCI_" & m_CANMatrix.TCIVersion
                    Me.MarcoPaola.ExportFileInfixedLocation("paralist", "Log", Me.m_CANMatrix.ParametersList, NameFile)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try

            Else
                If IO.Directory.GetFiles("Log", "*.paralog").Length <> 0 Then
                    Dim fileinfo As IO.FileInfo = New IO.FileInfo(IO.Directory.GetFiles("Log", "*.paralog")(0))



                    Try
                        MarcoPaola.ImportFileFromFixedLocation(fileinfo.FullName, ParameterChangeringLogs)
                        ParameterChangeringLogs.isUpdated = False

                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                End If

                Try
                    Dim NameFile As String = m_CANMatrix.ClientName & "_" & m_CANMatrix.OMEName & "_" & m_CANMatrix.ApplicationName & "_" & m_CANMatrix.SWVersion & "_" & "TCI_" & m_CANMatrix.TCIVersion
                    Me.MarcoPaola.ExportFileInfixedLocation("paralist", "Log", Me.m_CANMatrix.ParametersList, NameFile)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try


            End If


        Catch ex As Exception
            MsgBox("Log can not be created, Failure of system access")
        End Try

    End Sub
    Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click

        Dim stsResult As TPCANStatus

        ' Connects a selected PCAN-Basic channel
        '
        m_PcanHandle = Convert.ToUInt16("51", 16)
        m_Baudrate = TPCANBaudrate.PCAN_BAUD_250K

        stsResult = PCANBasic.Initialize(m_PcanHandle, m_Baudrate)




        If stsResult <> TPCANStatus.PCAN_ERROR_OK Then

            If stsResult <> TPCANStatus.PCAN_ERROR_CAUTION Then


                MessageBox.Show(GetFormatedError(stsResult))
            Else

                stsResult = TPCANStatus.PCAN_ERROR_OK
            End If

        Else
            ' Prepares the PCAN-Basic's PCAN-Trace file
            '

        End If

        ' Sets the connection status of the main-form
        '
        Me.ConnectionStatus = (stsResult = TPCANStatus.PCAN_ERROR_OK)
        SetConnectionStatus(stsResult = TPCANStatus.PCAN_ERROR_OK)

    End Sub


    Private Function GetFormatedError(ByVal [error] As TPCANStatus) As String
        Dim strTemp As StringBuilder

        ' Creates a buffer big enough for a error-text
        '
        strTemp = New StringBuilder(256)
        ' Gets the text using the GetErrorText API function
        ' If the function success, the translated error is returned. If it fails,
        ' a text describing the current error is returned.
        '
        If PCANBasic.GetErrorText([error], 0, strTemp) <> TPCANStatus.PCAN_ERROR_OK Then
            Return String.Format("An error occurred. Error-code's text ({0:X}) couldn't be retrieved", [error])
        Else
            Return strTemp.ToString()
        End If
    End Function


    Private Sub SetConnectionStatus(ByVal bConnected As Boolean)
        ' Buttons
        '
        ButtonConnect.Enabled = Not bConnected
        ButtonGenerateReport.Enabled = bConnected
        ButtonRelease.Enabled = bConnected
        lstMessages.Enabled = bConnected
        TextBoxInfoACT.Enabled = bConnected
        TextBoxInfoACT.Text = ""
        ContextMenuStrip1.Enabled = bConnected

        Me.IDHere = ""



        ' Display messages in grid
        '


        tmrDisplay.Enabled = bConnected

        tmrRead.Enabled = bConnected


        If bConnected Then
            Me.TextBoxInfoACT.Text += "Actuator Connected "

            '
            If m_SendTread IsNot Nothing Then
                m_SendTread.Abort()
                m_SendTread.Join()
                m_SendTread = Nothing

            End If




            m_FeedBackResults = New FeedbackResults(m_CANMatrix)





        Else

            Me.TextBoxInfoACT.Text += vbCrLf + "No Connection"


        End If




    End Sub


    Public Function GetIDFromFeedback() As String

        If m_LastMsgsList.Count > 0 And m_LastMsgsList.Count < 15 Then
            Dim tempIDStatus As New List(Of String)
            Dim tempIDFaultCode As New List(Of String)

            For Each msg As MessageStatus In m_LastMsgsList
                If msg.IdString.Replace("h", " ").Trim.Contains("08FF10") Then

                    tempIDStatus.Add(msg.IdString.Replace("h", " ").Trim.Substring(6))

                End If


                If msg.IdString.Replace("h", " ").Trim.Contains("18FF0A") Then

                    tempIDFaultCode.Add(msg.IdString.Replace("h", " ").Trim.Substring(6))

                End If


            Next


            For Each St In tempIDStatus

                For Each STF In tempIDFaultCode
                    If St = STF Then

                        Me.TextBoxInfoACT.Text += vbCrLf & "ID: " & St
                        Return St
                    End If

                Next

            Next
            Return ""


        End If

        Return ""
    End Function


    Public Sub SpecificCommandReadSequence()

        Dim countTotal As Integer = 0
        Dim limite As Integer = 2000000
        Dim Request As String = m_CANMatrix.Specific_CommandDict.Item("SW Version 1")

        Dim MyMsg As New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)

        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)
            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If

        Loop

        Dim SWversion1 As String = m_FeedBackResults.TrimACT2ToolMsg(4)
        Dim byte1 As String = SWversion1.Substring(0, 2)
        Dim byte2 As String = SWversion1.Substring(2, 2)
        Dim byte3 As String = SWversion1.Substring(4, 2)
        Dim byte4 As String = SWversion1.Substring(6, 2)

        SWversion1 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16)) & Chr(Convert.ToInt16(byte3, 16)) & Chr(Convert.ToInt16(byte4, 16))


        Request = m_CANMatrix.Specific_CommandDict.Item("SW Version 2")
        MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)

            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If
        Loop
        Dim SWversion2 As String = m_FeedBackResults.TrimACT2ToolMsg(4)
        byte1 = SWversion2.Substring(0, 2)
        byte2 = SWversion2.Substring(2, 2)
        byte3 = SWversion2.Substring(4, 2)
        byte4 = SWversion2.Substring(6, 2)

        SWversion2 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16)) & Chr(Convert.ToInt16(byte3, 16)) & Chr(Convert.ToInt16(byte4, 16))



        Request = m_CANMatrix.Specific_CommandDict.Item("SW Version 3")
        MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)
            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If

        Loop
        Dim SWversion3 As String = m_FeedBackResults.TrimACT2ToolMsg(4)
        byte1 = SWversion3.Substring(0, 2)
        byte2 = SWversion3.Substring(2, 2)
        byte3 = SWversion3.Substring(4, 2)
        byte4 = SWversion3.Substring(6, 2)

        SWversion3 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16)) & Chr(Convert.ToInt16(byte3, 16)) & Chr(Convert.ToInt16(byte4, 16))





        Me.m_SWversionInACT = SWversion1 & SWversion2 & SWversion3

        Me.TextBoxInfoACT.Text += vbCrLf + "SW version Actuator: " + Me.m_SWversionInACT


        Request = m_CANMatrix.Specific_CommandDict.Item("Serial Number 1")
        MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)
            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If

        Loop
        Dim SN1 As String = m_FeedBackResults.TrimACT2ToolMsg(4)
        byte1 = SN1.Substring(0, 2)
        byte2 = SN1.Substring(2, 2)
        byte3 = SN1.Substring(4, 2)
        byte4 = SN1.Substring(6, 2)

        SN1 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16)) & Chr(Convert.ToInt16(byte3, 16)) & Chr(Convert.ToInt16(byte4, 16))

        Request = m_CANMatrix.Specific_CommandDict.Item("Serial Number 2")
        MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)

            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If
        Loop
        Dim SN2 As String = m_FeedBackResults.TrimACT2ToolMsg(4)
        byte1 = SN2.Substring(0, 2)
        byte2 = SN2.Substring(2, 2)
        byte3 = SN2.Substring(4, 2)
        byte4 = SN2.Substring(6, 2)

        SN2 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16)) & Chr(Convert.ToInt16(byte3, 16)) & Chr(Convert.ToInt16(byte4, 16))

        Request = m_CANMatrix.Specific_CommandDict.Item("Serial Number 3")
        MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
        WriteFrame(MyMsg)
        countTotal = 0
        Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)
            countTotal += 1
            If countTotal >= limite Then
                Exit Sub
            End If

        Loop
        Dim SN3 As String = m_FeedBackResults.TrimACT2ToolMsg(2)
        byte1 = SN3.Substring(0, 2)
        byte2 = SN3.Substring(2, 2)


        SN3 = Chr(Convert.ToInt16(byte1, 16)) & Chr(Convert.ToInt16(byte2, 16))

        Me.m_SerialNumberInACT = SN1 & SN2 & SN3
        Me.TextBoxInfoACT.Text += vbCrLf + "SN Actuator: " + Me.m_SerialNumberInACT
        Me.TextBoxInfoACT.ScrollToCaret()



        'Juge if CANMAX match 

        Try
            Request = m_CANMatrix.Specific_CommandDict.Item("Operating Time")
            MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
            WriteFrame(MyMsg)
            countTotal = 0
            Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)
                countTotal += 1
                If countTotal >= limite Then
                    Exit Sub
                End If

            Loop

            Dim Masg As String = m_FeedBackResults.TrimACT2ToolMsg(4)

            Me.m_TimeSincePowerOn = Convert.ToInt16(Masg, 16)

            Me.TextBoxInfoACT.Text += vbCrLf + "Time Since Power on: " + Me.m_TimeSincePowerOn

            Request = m_CANMatrix.Specific_CommandDict.Item("Amount of Power On")
            MyMsg = New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)
            WriteFrame(MyMsg)
            countTotal = 0
            Do Until m_FeedBackResults.AdressInACT2Tool = Request.Replace("_", "").Substring(0, 4)

                countTotal += 1
                If countTotal >= limite Then
                    Exit Sub
                End If
            Loop

            Dim Masg1 As String = m_FeedBackResults.TrimACT2ToolMsg(4)

            Me.m_TimesPowerOn = Convert.ToInt16(Masg1, 16)
            Me.TextBoxInfoACT.Text += vbCrLf + "Power on times in Total: " + Me.m_TimesPowerOn


        Catch ex As Exception

        End Try







    End Sub



    Private Function WriteFrame(Msg As Object)


        Try

            Dim MsgBody As MsgContainer = TryCast(Msg, MsgContainer)

            ' We get so much data as the Len of the message
            '
            'For I As Integer = 0 To GetLengthFromDLC(CANMsg.LEN, True) - 1
            'txtbCurrentTextBox = DirectCast(Me.Controls.Find("txtData" + I.ToString(), True)(0), TextBox)
            'CANMsg.DATA(I) = Convert.ToByte(txtbCurrentTextBox.Text, 16)
            'Next

            If MsgBody.is_Cyclycal Then
                Do
                    Thread.Sleep(MsgBody.Interval)

                    PCANBasic.Write(m_PcanHandle, MsgBody.CANMsg)


                Loop Until PCANBasic.Write(m_PcanHandle, MsgBody.CANMsg) <> TPCANStatus.PCAN_ERROR_OK And Me.m_isCyclycal <> True
                Return TPCANStatus.PCAN_ERROR_OK

            End If

            ' The message is sent to the configured hardware
            '
            Return PCANBasic.Write(m_PcanHandle, MsgBody.CANMsg)
            'If (stsresult = TPCANStatus.PCAN_ERROR_OK) Then
            'IncludeTextMessage("message was successfully sent")
            'Else
            ' an error occurred.  we show the error.
            '
            'MessageBox.Show(GetFormatedError(stsresult))
            'End If

        Catch ex As Exception
            Return TPCANStatus.PCAN_ERROR_UNKNOWN
        End Try

    End Function

    Private Sub ButtonRelease_Click(sender As Object, e As EventArgs) Handles ButtonRelease.Click
        Me.TextBoxInfoACT.Text = ""

        PCANBasic.Uninitialize(m_PcanHandle)

        If m_ReadThread IsNot Nothing Then
            m_ReadThread.Abort()
            m_ReadThread.Join()
            m_ReadThread = Nothing
        End If

        ' Sets the connection status of the main-form
        '
        Me.ConnectionStatus = False
        SetConnectionStatus(False)

    End Sub

    Private Sub ButtonGenerateReport_Click(sender As Object, e As EventArgs) Handles ButtonGenerateReport.Click
        If Me.ConnectionStatus Then
            CheckForIllegalCrossThreadCalls = False

            Dim mythread As New Threading.Thread(AddressOf GeneratingReport)
            mythread.SetApartmentState(Threading.ApartmentState.STA)

            mythread.Start()

        Else
            MsgBox("No Communication to CAN bus", MsgBoxStyle.OkOnly, "Information")
        End If

    End Sub

    Private Sub tmrDisplay_Tick(sender As Object, e As EventArgs) Handles tmrDisplay.Tick
        DisplayMessages()

        If IDHere = "" Then

            IDHere = GetIDFromFeedback()

            If IDHere <> "" Then

                m_CANMatrix.ID = IDHere

                m_FeedBackResults.MyCanMatrix = m_CANMatrix

                CheckForIllegalCrossThreadCalls = False

                m_SendTread = New Thread(AddressOf SpecificCommandReadSequence)
                m_SendTread.Start()

            End If


        End If




    End Sub


    Private Sub DisplayMessages()
        Dim lviCurrentItem As ListViewItem

        SyncLock m_LastMsgsList.SyncRoot
            For Each msgStatus As MessageStatus In m_LastMsgsList
                ' Get the data to actualize
                '
                '                If msgStatus.MarkedAsUpdated Then
                '                    msgStatus.MarkedAsUpdated = False

                lviCurrentItem = lstMessages.Items(msgStatus.Position)

                lviCurrentItem.SubItems(2).Text = GetLengthFromDLC(msgStatus.CANMsg.DLC, (msgStatus.CANMsg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_FD) = 0).ToString()
                lviCurrentItem.SubItems(3).Text = msgStatus.Count.ToString()
                lviCurrentItem.SubItems(4).Text = msgStatus.TimeString
                lviCurrentItem.SubItems(5).Text = msgStatus.DataString

                '                End If
            Next
        End SyncLock


    End Sub




    Public Shared Function GetLengthFromDLC(ByVal dlc As Integer, ByVal isSTD As Boolean)
        If dlc <= 8 Then
            Return dlc
        End If

        If (isSTD) Then
            Return 8
        End If

        Select Case dlc
            Case 9
                Return 12
            Case 10
                Return 16
            Case 11
                Return 20
            Case 12
                Return 24
            Case 13
                Return 32
            Case 14
                Return 48
            Case 15
                Return 64
            Case Else
                Return dlc
        End Select
    End Function

    Private Sub tmrRead_Tick(sender As Object, e As EventArgs) Handles tmrRead.Tick
        ReadMessages()
    End Sub


    Private Sub ReadMessages()
        Dim stsResult As TPCANStatus

        ' We read at least one time the queue looking for messages.
        ' If a message is found, we look again trying to find more.
        ' If the queue is empty or an error occurr, we get out from
        ' the dowhile statement.
        '			
        Do
            ' We execute the "Read" or "ReadFD" function of the PCANBasic
            '
            stsResult = ReadMessage()

            If (stsResult = TPCANStatus.PCAN_ERROR_ILLOPERATION) Then
                Exit Do
            End If

        Loop While ButtonRelease.Enabled AndAlso (Not Convert.ToBoolean(stsResult And TPCANStatus.PCAN_ERROR_QRCVEMPTY))


    End Sub


    Private Function ReadMessage() As TPCANStatus
        Dim CANMsg As TPCANMsg = Nothing
        Dim CANTimeStamp As TPCANTimestamp
        Dim stsResult As TPCANStatus

        ' We execute the "Read" function of the PCANBasic 
        '
        stsResult = PCANBasic.Read(m_PcanHandle, CANMsg, CANTimeStamp)
        If (stsResult <> TPCANStatus.PCAN_ERROR_QRCVEMPTY) Then
            ' We process the received message
            '

            ProcessMessage(CANMsg, CANTimeStamp)

        End If

        Return stsResult
    End Function


    Private Sub ProcessMessage(ByVal theMsg As TPCANMsg, ByVal itsTimeStamp As TPCANTimestamp)
        Dim newMsg As TPCANMsgFD
        Dim newTimestamp As TPCANTimestampFD

        newMsg = New TPCANMsgFD()
        newMsg.DATA = CType(Array.CreateInstance(GetType(Byte), 64), Byte())
        newMsg.ID = theMsg.ID
        newMsg.DLC = theMsg.LEN
        For i As Integer = 0 To If(theMsg.LEN > 8, 7, theMsg.LEN - 1)
            newMsg.DATA(i) = theMsg.DATA(i)
        Next
        newMsg.MSGTYPE = theMsg.MSGTYPE

        newTimestamp = Convert.ToUInt64(itsTimeStamp.micros + 1000 * itsTimeStamp.millis + &H100000000 * 1000 * itsTimeStamp.millis_overflow)
        ProcessMessage(newMsg, newTimestamp)
    End Sub

    Private Sub ProcessMessage(ByVal theMsg As TPCANMsgFD, ByVal itsTimeStamp As TPCANTimestampFD)
        ' We search if a message (Same ID and Type) is 
        ' already received or if this is a new message
        '
        SyncLock m_LastMsgsList.SyncRoot
            For Each msg As MessageStatus In m_LastMsgsList
                If (msg.CANMsg.ID = theMsg.ID) And (msg.CANMsg.MSGTYPE = theMsg.MSGTYPE) Then
                    ' Messages of this kind are already received; we do an update
                    '

                    msg.Update(theMsg, itsTimeStamp)
                    msg.MarkedAsUpdated = True
                    m_FeedBackResults.ReadResults(msg)
                    Exit Sub
                End If
            Next

            ' Message not found. It will created
            '
            InsertMsgEntry(theMsg, itsTimeStamp)
        End SyncLock
    End Sub


    Private Sub InsertMsgEntry(ByVal newMsg As TPCANMsgFD, ByVal timeStamp As TPCANTimestampFD)
        Dim lviCurrentItem As ListViewItem
        Dim msgStsCurrentMsg As MessageStatus

        SyncLock m_LastMsgsList.SyncRoot
            ' We add this status in the last message list
            '
            msgStsCurrentMsg = New MessageStatus(newMsg, timeStamp, lstMessages.Items.Count)
            msgStsCurrentMsg.ShowingPeriod = True

            m_LastMsgsList.Add(msgStsCurrentMsg)

            m_FeedBackResults.ReadResults(msgStsCurrentMsg)
            ' Add the new ListView Item with the Type of the message
            '	
            Dim TypeStr As String = m_FeedBackResults.getFeedBackTypeStrByIfContain(msgStsCurrentMsg.IdString)

            lviCurrentItem = lstMessages.Items.Add(TypeStr)

            lviCurrentItem.BackColor = m_FeedBackResults.getFeedBackTypeColorByIfContain(msgStsCurrentMsg.IdString)
            ' We set the ID of the message
            '
            lviCurrentItem.SubItems.Add(msgStsCurrentMsg.IdString)
            ' We set the length of the Message
            '
            lviCurrentItem.SubItems.Add(GetLengthFromDLC(newMsg.DLC, (newMsg.MSGTYPE And TPCANMessageType.PCAN_MESSAGE_FD) = 0).ToString())
            ' we set the message count message (this is the First, so count is 1)            
            '
            lviCurrentItem.SubItems.Add(msgStsCurrentMsg.Count.ToString())
            ' Add time stamp information if needed
            '
            lviCurrentItem.SubItems.Add(msgStsCurrentMsg.TimeString)
            ' We set the data of the message. 	
            '
            lviCurrentItem.SubItems.Add(msgStsCurrentMsg.DataString)
        End SyncLock
    End Sub

    Private Sub CopySNAndSWToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopySNAndSWToolStripMenuItem.Click
        Dim text As String = "SW Version: " & Me.m_SWversionInACT & Chr(13) + Chr(10) & "SN: " & Me.m_SerialNumberInACT
        Clipboard.SetText(text)
    End Sub


    Public Sub GeneratingReport()



        myprogress = New Dialog_progress()
        myprogress.ValueProgress(0, "Start to read Diagnostics Table")
        myprogress.Show()




        ReadValues(0)
        myprogress.ValueProgress(10, "Start to read Ring Buffer")
        ReadValues(1)
        myprogress.ValueProgress(30, "Start to read Histogram")
        ReadValues(2)
        myprogress.ValueProgress(40, "Reading EEPROM finished, Start to generate EXCEL")


        Dim MacroPoloHere = New MacroPalo


        Dim myExcelBook As Excel.Workbook = MacroPoloHere.CreatExcelBook()

        Dim mySheetHistogramm As Excel.Worksheet = myExcelBook.Worksheets(1)
        mySheetHistogramm.Name = "Histogramm"

        Dim mySheetRingBuffer As Excel.Worksheet = myExcelBook.Worksheets.Add()
        mySheetRingBuffer.Name = "RingBuffer"
        Dim mySheetDtable As Excel.Worksheet = myExcelBook.Worksheets.Add()
        mySheetDtable.Name = "Diagnostics Table"
        Dim mySheetSyn As Excel.Worksheet = myExcelBook.Worksheets.Add()
        mySheetSyn.Name = "Synthesis of diagnostics"
        myprogress.ValueProgress(60, "Initialisation of EXCEL file finished")

        FillExcelSheets(mySheetSyn, mySheetDtable, mySheetRingBuffer, mySheetHistogramm)
        myprogress.ValueProgress(100, "Generation of EXCEL file finished")


        MacroPoloHere.SaveExcel()
        TextBoxInfoACT.Text += vbCrLf & "Reading Analysis Report Finished"



    End Sub

    Public Sub ReadValueInEEPROM(Para As Integer, IndexRow As Integer, Optional IndexColum As Integer = 0, Optional RingBufferZone As Integer = 0)

        Dim Request As String = m_CANMatrix.GetReadEEPROMCommand(Para, IndexRow, IndexColum, RingBufferZone)

        If Request IsNot Nothing Then
            Dim MyMsg As New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)

            WriteFrame(MyMsg)
        End If

    End Sub


    Public Sub ReadValues(indexTab As Integer)
        Try


            Select Case indexTab
                Case 0

                    For row = 0 To Me.m_CANMatrix.DiagnoticRowNumber - 1

                        For col = 0 To 15
                            Do Until m_FeedBackResults.AdressInACT2Tool = m_CANMatrix.GetReadEEPROMCommandAdress(0, row, col).Replace("_", "")

                                ReadValueInEEPROM(0, row, col)

                                For i As Integer = 0 To 10000000
                                    i = i + 1
                                Next


                            Loop


                            Me.DiagTableArray(row, col) = m_FeedBackResults.TrimACT2ToolMsg(1)



                        Next
                    Next

                Case 1
                    For row = 0 To Me.m_CANMatrix.RingBufferRowNumber - 1

                        For col = 0 To 15

                            Do Until m_FeedBackResults.AdressInACT2Tool = m_CANMatrix.GetReadEEPROMCommandAdress(1, row, col).Replace("_", "")

                                ReadValueInEEPROM(1, row, col)

                                For i As Integer = 0 To 10000000
                                    i = i + 1
                                Next


                            Loop

                            Me.RingBufferArray1(row, col) = m_FeedBackResults.TrimACT2ToolMsg(1)

                            Do Until m_FeedBackResults.AdressInACT2Tool = m_CANMatrix.GetReadEEPROMCommandAdress(1, row, col, 1).Replace("_", "")

                                ReadValueInEEPROM(1, row, col, 1)

                                For i As Integer = 0 To 10000000
                                    i = i + 1
                                Next


                            Loop

                            Me.RingBufferArray2(row, col) = m_FeedBackResults.TrimACT2ToolMsg(1)

                        Next
                    Next

                Case 2
                    For row = 0 To Me.m_CANMatrix.HistogramRowNumber - 1


                        Do Until m_FeedBackResults.AdressInACT2Tool = m_CANMatrix.GetReadEEPROMCommandAdress(2, row).Replace("_", "")

                            ReadValueInEEPROM(2, row)

                            For i As Integer = 0 To 100000000
                                i = i + 1
                            Next


                        Loop


                        Me.HistogrimArray(row) = m_FeedBackResults.TrimACT2ToolMsg(4)



                    Next


                    IsHistogramReadingFinished = True
            End Select


        Catch ex As Exception
            MsgBox(ex.Message,, "Errors")
        End Try
    End Sub


    Public Sub FillExcelSheets(ByRef SheetS As Excel.Worksheet, ByRef SheetD As Excel.Worksheet, ByRef SheetR As Excel.Worksheet, ByRef SheetH As Excel.Worksheet)
        With SheetS
            .Range("A1:A10").Interior.Color = Color.SkyBlue

            .Cells(1, 1).Value = "Project info"

            .Cells(1, 2).Value = m_CANMatrix.ClientName & "-" & m_CANMatrix.ApplicationName & "-" & m_CANMatrix.OMEName

            .Cells(2, 1).Value = "SW Version in ACT"

            .Cells(2, 2).Value = m_SWversionInACT
            .Cells(3, 1).Value = "SN in ACT"
            .Cells(3, 2).Value = m_SerialNumberInACT
            .Cells(4, 1).Value = "Date of Reading"
            .Cells(4, 2).Value = Date.Today.ToShortDateString

            .Cells(6, 1).Value = "CANMAX MATCH ?"
            .Cells(6, 2).Value = "Good"

            Dim Configg = New ConfigOfCANBOZ()
            .Cells(7, 1).Value = "CANBOZ Version"
            .Cells(7, 2).Value = Configg.CanBozVersion

            .Cells(8, 1).Value = "Hours Since Power On"
            .Cells(8, 2).Value = m_TimeSincePowerOn

            .Cells(9, 1).Value = "Power On Times"
            .Cells(9, 2).Value = m_TimesPowerOn

            .Cells(10, 1).Value = "Recorder"
            .Cells(10, 2).Value = "Please Input"
            .Columns(1).AutoFit()
            .Columns(2).AutoFit()

            .Range("A1:B10").HorizontalAlignment = 3
            .Range("A1:B10").VerticalAlignment = 3



        End With

        Dim ParaRange As Excel.Range = SheetS.Range(SheetS.Cells(1, 4), SheetS.Cells(m_CANMatrix.ParametersList.Count + 1, 8))

        With ParaRange
            .Cells(1, 1).Value = "Parameters"
            .Cells(1, 2).Value = "Default Value"
            .Cells(1, 3).Value = "Current Value in ACT"
            .Cells(1, 4).Value = "Value Modified ?"
            SheetS.Range(.Cells(1, 1), .Cells(1, 4)).Interior.Color = Color.SkyBlue
            Dim index = 2
            For Each para As ParameterProperty In m_CANMatrix.ParametersList
                Dim currentValue = Me.ReadCurrentValueOfPara(para)
                If currentValue IsNot Nothing Then
                    .Cells(index, 1).Value = para.Name
                    If para.DefaultValue = "" Then
                        .Cells(index, 2).value = "No default value"
                    Else
                        .Cells(index, 2).value = "'" & para.DefaultValue
                    End If

                    .Cells(index, 3).value = "'" & currentValue
                    .Cells(index, 4).value = Not (currentValue = para.DefaultValue)
                    If currentValue = para.DefaultValue Then
                        SheetS.Range(.Cells(index, 1), .Cells(index, 1)).Interior.Color = Color.SkyBlue
                    Else

                        SheetS.Range(.Cells(index, 1), .Cells(index, 1)).Interior.Color = Color.LightPink
                        SheetS.Range(.Cells(index, 4), .Cells(index, 4)).Interior.Color = Color.LightPink
                    End If
                    index = index + 1
                End If

            Next




        End With
        ParaRange.HorizontalAlignment = 1
        ParaRange.VerticalAlignment = 1
        ParaRange.Columns(1).AutoFit
        ParaRange.Columns(2).AutoFit

        ParaRange.Columns(3).AutoFit
        ParaRange.Columns(4).AutoFit



        With SheetD
            ' Preparing layout 

            Dim AllRange As Excel.Range = .Range(.Cells(1, 1), .Cells(17, 17))
            AllRange.VerticalAlignment = 3
            AllRange.HorizontalAlignment = 3

            .Range("A1").Interior.Color = Color.SkyBlue

            For i = 2 To 17
                .Cells(i, 1).Value = Me.m_CANMatrix.DignosticsTableRowLabels(i - 2)

                .Range(.Cells(i, 1), .Cells(i, 1)).Interior.Color = Color.SkyBlue
            Next
            .Columns(1).AutoFit()
            Dim index As Integer = 2
            For Each item In m_CANMatrix.DiagnoticTableColumLabels
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Merge()

                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Cells(1, 1).Value = item.Key
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Interior.Color = Color.SkyBlue
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Columns(1).AutoFit()
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).VerticalAlignment = 3
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).HorizontalAlignment = 3
                index = index + item.Value
            Next


            Dim DataRange As Excel.Range = .Range(.Cells(2, 2), .Cells(17, 17))

            For i = 1 To Me.DiagTableArray.GetLength(0)
                For j = 1 To 16
                    DataRange.Cells(i, j).value = "'" & Me.DiagTableArray(i - 1, j - 1)
                Next
            Next
        End With



        ' Preparing layout 
        'SheetR
        Dim RangePage1 As Excel.Range = SheetR.Range(SheetR.Cells(1, 1), SheetR.Cells(17, 17))


        RangePage1.Range(RangePage1.Cells(1, 1), RangePage1.Cells(1, 1)).Interior.Color = Color.SkyBlue
        RangePage1.Cells(1, 1).value = "Page 1"
        RangePage1.HorizontalAlignment = 3
        RangePage1.VerticalAlignment = 3
        With RangePage1
            For i = 2 To 17
                .Cells(i, 1).Value = (i - 1).ToString
                .Range(.Cells(i, 1), .Cells(i, 1)).Interior.Color = Color.SkyBlue
            Next

            Dim index As Integer = 2
            For Each item In m_CANMatrix.DiagnoticTableColumLabels
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Merge()
                If index = 2 Then
                    .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Cells(1, 1).Value = "Error Type"
                Else
                    .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Cells(1, 1).Value = item.Key
                End If

                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Interior.Color = Color.SkyBlue
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).Columns.AutoFit()
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).VerticalAlignment = 3
                .Range(.Cells(1, index), .Cells(1, index + item.Value - 1)).HorizontalAlignment = 3
                index = index + item.Value
            Next


            Dim DataRange As Excel.Range = .Range(.Cells(2, 2), .Cells(17, 17))

            For i = 1 To Me.RingBufferArray1.GetLength(0)
                For j = 1 To 16
                    DataRange.Cells(i, j).value = "'" & Me.RingBufferArray1(i - 1, j - 1)
                Next
            Next
        End With

        Dim RangePage2 As Excel.Range = SheetR.Range(SheetR.Cells(20, 1), SheetR.Cells(36, 17))


        SheetR.Range(RangePage2.Cells(1, 1), RangePage2.Cells(1, 1)).Interior.Color = Color.SkyBlue
        RangePage2.Cells(1, 1).value = "Page 2"
        RangePage2.HorizontalAlignment = 3
        RangePage2.VerticalAlignment = 3
        With RangePage2
            Dim i = 2
            For i = 2 To 17
                .Cells(i, 1).Value = (i - 1).ToString
                SheetR.Range(RangePage2.Cells(i, 1), RangePage2.Cells(i, 1)).Interior.Color = Color.SkyBlue
            Next

            Dim index As Integer = 2
            For Each item In m_CANMatrix.DiagnoticTableColumLabels
                SheetR.Range(RangePage2.Cells(1, index), RangePage2.Cells(1, index + item.Value - 1)).Merge()
                If index = 2 Then
                    SheetR.Range(RangePage2.Cells(1, index), RangePage2.Cells(1, index + item.Value - 1)).Cells(1, 1).Value = "Error Type"
                Else
                    SheetR.Range(RangePage2.Cells(1, index), RangePage2.Cells(1, index + item.Value - 1)).Cells(1, 1).Value = item.Key
                End If

                SheetR.Range(RangePage2.Cells(1, index), RangePage2.Cells(1, index + item.Value - 1)).Interior.Color = Color.SkyBlue
                SheetR.Range(RangePage2.Cells(1, index), RangePage2.Cells(1, index + item.Value - 1)).Columns(1).AutoFit()

                index = index + item.Value
            Next


            Dim DataRange As Excel.Range = SheetR.Range(RangePage2.Cells(2, 2), RangePage2.Cells(17, 17))

            For i = 1 To Me.RingBufferArray2.GetLength(0)
                For j = 1 To 16
                    DataRange.Cells(i, j).value = "'" & Me.RingBufferArray2(i - 1, j - 1)
                Next
            Next
        End With


        With SheetH

            SheetH.Range("A1:C16").VerticalAlignment = 3
            SheetH.Range("A1:C16").HorizontalAlignment = 3

            .Range("A1:F1").Interior.Color = Color.SkyBlue


            .Cells(2, 1).Value = "Temperature"

            .Cells(7, 1).Value = "Coil Current"

            .Cells(12, 1).Value = "Position"



            For j = 2 To Me.m_CANMatrix.HistogramRowNumber + 1
                .Cells(j, 2).Value = Me.m_CANMatrix.HistogramRangeStringArray(j - 2)
            Next

            Dim sumTemp As Integer = 0

            For j = 2 To Me.m_CANMatrix.HistogramRowNumber + 1

                Dim valueToStore As Integer


                valueToStore = Convert.ToInt32(Me.HistogrimArray(j - 2), 16)


                If j >= 7 Then
                    valueToStore = valueToStore * 0.32
                End If

                sumTemp = sumTemp + valueToStore

                If j = 6 Then
                    .Cells(j, 5).Value = sumTemp
                    .Cells(j, 6).Value = sumTemp / 3600
                    sumTemp = 0
                End If

                If j = 11 Then
                    .Cells(j, 5).Value = sumTemp
                    .Cells(j, 6).Value = sumTemp / 3600
                    sumTemp = 0
                End If

                If j = 16 Then
                    .Cells(j, 5).Value = sumTemp
                    .Cells(j, 6).Value = sumTemp / 3600
                    sumTemp = 0
                End If

                .Cells(j, 4).Value = valueToStore
            Next




            .Cells(1, 1).Value = "Field"

            .Cells(1, 2).Value = "Range"

            .Cells(1, 2).Value = "Data"

            .Cells(1, 4).Value = "Time(s)"

            .Cells(1, 5).Value = "Sum(s)"

            .Cells(1, 6).Value = "Sum(h)"
            For i = 2 To 6
                SheetH.Range(.Cells(i + 5, 1), .Cells(i + 5, 6)).Interior.Color = Color.SkyBlue

            Next




            For i = 2 To HistogrimArray.Length + 1

                .Cells(i, 3).value = "'" & Me.HistogrimArray(i - 2)

            Next

            .Columns(3).Autofit()
            .Columns(2).Autofit()
            .Columns(1).Autofit()
            Try
                Dim chartpage As Excel.Chart
                Dim xlCharts As Excel.ChartObjects
                Dim myChart As Excel.ChartObject
                Dim chartRange As Excel.Range

                xlCharts = .ChartObjects

                myChart = xlCharts.Add(400, 0, 400, 250)
                chartpage = myChart.Chart
                chartRange = .Range("B2: B6, D2: D6")
                chartpage.SetSourceData(Source:=chartRange)
                chartpage.ChartType = Excel.XlChartType.xlBarClustered

                chartpage.HasTitle = True
                chartpage.ChartTitle.Characters.Text = "Temperature"
                chartpage.FullSeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(Color.OrangeRed.R, Color.OrangeRed.G, Color.OrangeRed.B)
                'chartpage.ChartArea.Interior.Color = RGB(Color.OrangeRed.R, Color.OrangeRed.G, Color.OrangeRed.B)
                chartpage.HasLegend = False
                chartpage.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary).HasTitle = False
                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).HasTitle = True

                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "Time (s)"
                chartpage.SetElement(Microsoft.Office.Core.MsoChartElementType.msoElementDataLabelInsideEnd)


                myChart = xlCharts.Add(0, 250, 400, 250)
                chartpage = myChart.Chart
                chartRange = .Range("B7: B11, D7: D11")
                chartpage.SetSourceData(Source:=chartRange)
                chartpage.ChartType = Excel.XlChartType.xlBarClustered

                chartpage.HasTitle = True
                chartpage.ChartTitle.Characters.Text = "Coil Current"
                chartpage.FullSeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(Color.Green.R, Color.Green.G, Color.Green.B)
                'chartpage.ChartArea.Interior.Color = RGB(Color.OrangeRed.R, Color.OrangeRed.G, Color.OrangeRed.B)
                chartpage.HasLegend = False
                chartpage.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary).HasTitle = False
                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).HasTitle = True

                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "Time (s)"
                chartpage.SetElement(Microsoft.Office.Core.MsoChartElementType.msoElementDataLabelInsideEnd)

                myChart = xlCharts.Add(400, 250, 400, 250)
                chartpage = myChart.Chart
                chartRange = .Range("B12: B16, D12: D16")
                chartpage.SetSourceData(Source:=chartRange)
                chartpage.ChartType = Excel.XlChartType.xlBarClustered

                chartpage.HasTitle = True
                chartpage.ChartTitle.Characters.Text = "Position"
                chartpage.FullSeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(Color.BlueViolet.R, Color.BlueViolet.G, Color.BlueViolet.B)
                'chartpage.ChartArea.Interior.Color = RGB(Color.OrangeRed.R, Color.OrangeRed.G, Color.OrangeRed.B)
                chartpage.HasLegend = False
                chartpage.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary).HasTitle = False
                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).HasTitle = True

                chartpage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "Time (s)"
                chartpage.SetElement(Microsoft.Office.Core.MsoChartElementType.msoElementDataLabelInsideEnd)


            Catch ex As Exception
                MsgBox(ex.Message)
            End Try



        End With

        'Generate the Synthsis Sheet. 

        ' To be done 

    End Sub



    Public Function ReadCurrentValueOfPara(Para As ParameterProperty) As String
        If ConnectionStatus Then
            Try

                Do

                    Me.ReadValue(Para.Name)

                    For i As Integer = 0 To 100000000
                        i = i + 1
                    Next


                Loop Until m_FeedBackResults.AdressInACT2Tool = Para.Adress.Replace("_", "")



                'Me.m_parent.ReadValue(Name)


                Dim results As String = m_FeedBackResults.TrimACT2ToolMsg(Para.Length)
                Return results
                Para.updateValue(results, results)
            Catch ex As Exception

                Return Nothing
            End Try

        End If

    End Function



    Public Sub ReadValue(typeRead1 As String)

        Dim Request As String = m_CANMatrix.GetACT2ToolCommand_Read(typeRead1)

        If Request IsNot Nothing Then
            Dim MyMsg As New MsgContainer(m_CANMatrix.ToolToActuator, Request.Replace("_", ""), 8, m_CANMatrix)

            WriteFrame(MyMsg)
        End If

    End Sub

    Private Sub AppendSNSWToFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AppendSNSWToFileToolStripMenuItem.Click
        Dim strArr As String()
        Dim index As Integer = 0
        Me.MarcoPaola.ReadTXTArrayInfixedLocation("Log", "SN and SW Records", strArr)
        index = strArr.Length + 1
        For Each line As String In strArr
            If line = "" Then Return
            Dim a As String() = line.Split(",")
            If m_SerialNumberInACT.Trim() = a(1).Trim Then

                TextBoxInfoACT.Text += vbCrLf & "SN/SW Record Already Exsits"
                Return

            End If


        Next

        Dim str As String = index & "," & Me.m_SerialNumberInACT & "," & Me.m_SWversionInACT & "," & Today.Now

        Me.MarcoPaola.SaveToTXTInfixedLocation("Log", str, "SN and SW Records")
        TextBoxInfoACT.Text += vbCrLf & "SN/SW Records Successfully"
    End Sub

    Private Sub OpenSNSWRecordToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenSNSWRecordToolStripMenuItem.Click
        Me.MarcoPaola.OpenTXTFileInfixedLocation("Log", "SN and SW Records")
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()

        Me.TextBoxInfoACT.Text = ""

        PCANBasic.Uninitialize(m_PcanHandle)

        If m_ReadThread IsNot Nothing Then
            m_ReadThread.Abort()
            m_ReadThread.Join()
            m_ReadThread = Nothing
        End If

        ' Sets the connection status of the main-form
        '

    End Sub

    Private Sub SetIDMannuallyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SetIDMannuallyToolStripMenuItem.Click
        Dim diag1 As New Form_SetIDMannully(Me)

        diag1.ShowDialog()
    End Sub


    Public COSSS As Func(Of Double, Double) = Function(ByVal i As Double)
                                                  Return Math.Cos(i)
                                              End Function
    Private Sub PlotTestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PlotTestToolStripMenuItem.Click
        Dim myModel = New PlotModel
        myModel.Title = "New Plot"
        myModel.Series.Add(New FunctionSeries(COSSS, 0, 10, 0.1, "cos(x)"))


        Dim PltFrom = New Form_ShowPlot()
        PltFrom.PlotView1.Model = myModel
        PltFrom.Show()
    End Sub
End Class